
import session from "util/session.js";

// 检测本地存储大小
const checkLocalStorageSize = (name,data) =>{
  let size = 0;
  for (let item in window.localStorage) {
      if (window.localStorage.hasOwnProperty(item)) {
          size += window.localStorage.getItem(item).length;
      }
  }
  let sizeUsed = (size / 1024).toFixed(2);
  return new Promise((resolve,reject) => {
    if (sizeUsed > 3 * 1000 || Array.isArray(data) && data.length > 500) {
      console.log('当前localStorage容量为' + sizeUsed + 'KB');
      console.log('本地存储已满，清除缓存记录！');
      resolve('clear')
    } else {
      reject('save')
    }
  })
};
const setErrorInfo = function (errorObj){
    const { name, message } = errorObj
  if (name!= 'api_send'){
    myAlert({name,message});
    console.error(errorObj);
  }
  errorObj.time = new Date();
  let err_arr = [];
  let err_info = session.getLocal('errInfo');
  // console.log(err_info);
  checkLocalStorageSize('errInfo', err_info).then((res) => {
    if (err_info) {
      let len = err_info.length;
      if (len && 1 < len) {
        let end = Math.ceil(len / 2);
        err_arr = err_info.slice(0, end);
      }
    }
    err_arr.unshift(errorObj);
    session.setLocal('errInfo',err_arr);
  }).catch((err) => {
    if (err_info){
      err_arr = err_info;
    }
    err_arr.unshift(errorObj);
    session.setLocal('errInfo',err_arr);
  })
}
// 错误信息捕获收集
/**
 * @param {String} errorMessage  错误信息
 * @param {String} scriptURI   出错的文件
 * @param {Long}  lineNumber   出错代码的行号
 * @param {Long}  columnNumber  出错代码的列号
 * @param {Object} errorObj    错误的详细信息，Anything
 */
window.addEventListener('error', function (e) {
    console.log(e);
    let name, stack;
    if (e.error) {
        stack = e.error.stack.split("\n");
    }
    let errObj = {
        name: e.type || null,
        message: e.message || null,
        script: e.filename || null,
        line: e.lineno || null,
        column: e.colno || null,
        stack: stack || null,
    }
    if (errObj.message.includes('ResizeObserver') || errObj.message.includes('Script error')) {
        return false;
    }

    // 不包含高德地图的报错
    if (errObj.message.includes("Cannot read property 'xc' of null")) {
        return false;
    }
    setErrorInfo(errObj);
} )
// window.onerror = function (errorMessage, scriptURI, lineNumber, columnNumber, errorObj) {
//     console.log(errorObj);
//     let name ,stack ;
//     if (errorObj){
//         name = errorObj.name;
//         stack = errorObj.stack.split("\n");
//     }
//     let errObj = {
//         name: name || null,
//         message: errorMessage || null,
//         script: scriptURI || null,
//         line: lineNumber || null,
//         column: columnNumber || null,
//         stack: stack || null,
//     }
//     setErrorInfo(errObj);
// }
window.addEventListener('unhandledrejection', event => {
    console.error(event);
    console.error(event.reason);
    // setErrorInfo(errorObj);
});
window.addEventListener('rejectionhandled', event => {
    console.error('rejection handled'); // 1秒后打印"rejection handled"
});
const catchError = (err, vm, info) => {
    // console.log(err);
    if(!err){
        setErrorInfo({name:'undefined'});
        return false;
    }
    let {   message, // 异常信息
            name, // 异常名称
            script,  // 异常脚本url
            line,  // 异常行号
            column,  // 异常列号
            stack  // 异常堆栈信息
        } = err;
        if (stack){
            stack = stack.split("\n");
        }
    let errorObj = {
        name:name || null,
        message:message || null,
        script:script || null,
        line:line || null,
        column:column || null,
        stack:stack || null,
    }
    setErrorInfo(errorObj);
};
const throwErr = (err, name = 'ajax-api') => {
    console.log(err);
    if (err === 'cancel' || Object.prototype.toString.call(err) === '[object String]') return false;
    let obj = {};
    // console.log(err);
   if (err && err.hasOwnProperty('code')){
        obj.name = name;
        obj.message = ('code:' + err.code + ' msg:' + err.msg);
        obj.script = err.rqtype;
        obj.stack = JSON.stringify(err);
    } else {
        obj = err;
    }
    catchError(obj);
    // alert(err);
}
export {
  catchError,
  throwErr,
  setErrorInfo
}

